package com.woniu.cms.auth.core.service.impl;

import com.woniu.cms.auth.core.entity.RbacRole;
import com.woniu.cms.auth.core.mapper.RbacRoleMapper;
import com.woniu.cms.auth.core.service.IRbacRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.cms.auth.core.vo.RoleVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lilili
 * @since 2022-09-16
 */
@Service
public class RbacRoleServiceImpl extends ServiceImpl<RbacRoleMapper, RbacRole> implements IRbacRoleService {
    @Resource
    private RbacRoleMapper roleMapper;
    @Transactional
    @Override
    public List<RbacRole> allByUserId(Integer userId) {
        List<RbacRole> list = roleMapper.allByUserId(userId);
        return list;
    }

    @Transactional
    @Override
    public RoleVo display(Integer userId) {
        List<RbacRole> all = roleMapper.selectList(null);
        List<RbacRole> allot = roleMapper.allByUserId(userId);
        List<RbacRole> unallot = new ArrayList<>();
        for (RbacRole r : all) {
            if(!allot.contains(r)){
                unallot.add(r);
            }
        }
        return new RoleVo().setAllot(all).setUnallot(unallot);
    }

    @Transactional
    @Override
    public boolean doAllot(Integer userId, Integer[] roleIds) {
        int i = roleMapper.doAllot(userId,roleIds);
        if(i == 0){
            throw new RuntimeException("分配角色失败");
        }
        return true;
    }

    @Transactional
    @Override
    public boolean doUnAllot(Integer userId, Integer[] roleIds) {
        int i = roleMapper.doUnAllot(userId,roleIds);
        if(i == 0){
            throw new RuntimeException("分配角色失败");
        }
        return true;
    }
}
